package com.open.redis.config.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collections;


/**
 * @author: liudong8
 * @Date: 2025/4/5 16:11
 * @Version: V1.0
 * @description: |
 */


@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 加锁
     *
     * @param key   锁的key
     * @param value 锁的value
     * @param time  锁的过期时间（秒）
     * @return
     */
    public Boolean lock(String key, String value, Long time) {
        Boolean lockStatus = redisTemplate.opsForValue().setIfAbsent(key, value, Duration.ofSeconds(time));
        return lockStatus;
    }

    /**
     * 释放锁
     *
     * @param key
     * @param value
     * @return
     */
    public Long unLock(String key, String value) {
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        Long releaseStatus = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        return releaseStatus;
    }
}
